package me.wang.qrcodepay;

import com.google.gson.Gson;
import org.apache.commons.lang.RandomStringUtils;
import org.bukkit.ChatColor;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerDropItemEvent;
import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.inventory.ItemStack;
import org.bukkit.plugin.Plugin;
import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.scheduler.BukkitRunnable;

import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;



public final class QRcodePay extends JavaPlugin implements Listener {

    public static Plugin plugin;
    public static HashMap<String,ItemStack[]> inv = new HashMap<String,ItemStack[]>();
    public static HashMap<String,String> orders = new HashMap<String,String>();
    public static HashMap<String,String> items = new HashMap<String,String>();

    @Override
    public void onEnable() {
        getServer().getPluginManager().registerEvents(this,this);
        plugin = me.wang.qrcodepay.QRcodePay.getPlugin(me.wang.qrcodepay.QRcodePay.class);


        if (!getDataFolder().exists()) {
            getDataFolder().mkdirs();
        }
        saveDefaultConfig();
        reloadConfig();
    }

    @Override
    public void onDisable() {

    }

    @EventHandler
    public static void click(PlayerInteractEvent e){

        if (inv.containsKey(e.getPlayer().getName())){
            e.setCancelled(true);
            new BukkitRunnable() {
                @Override
                public void run() {
                    e.getPlayer().getInventory().setContents(inv.get(e.getPlayer().getName()));
                    inv.remove(e.getPlayer().getName());
                    CheckPayment checkPayment = new CheckPayment(orders.get(e.getPlayer().getName()));
                    orders.remove(e.getPlayer().getName());
                    Gson gson = new Gson();
                    HashMap<String,Object> map = gson.fromJson(checkPayment.getResponse(),HashMap.class);
                    if (map.containsKey("status")){
                        if (map.get("status").toString().equalsIgnoreCase("1")){
                            e.getPlayer().sendMessage("支付成功！");
                            new BukkitRunnable() {
                                @Override
                                public void run() {
                                    plugin.getServer().dispatchCommand(plugin.getServer().getConsoleSender(),plugin.getConfig().getString(items.get(e.getPlayer().getName())+".command").replace("%player%",e.getPlayer().getName()));
                                }
                            }.runTask(plugin);

                            items.remove(e.getPlayer().getName());
                        }else{
                            e.getPlayer().sendMessage("支付失败！");
                        }
                    }else{
                        e.getPlayer().sendMessage("订单查询失败！");
                    }
                }
            }.runTaskAsynchronously(plugin);

        }
    }

    @EventHandler
    public static void drop(PlayerDropItemEvent e){
        if (inv.containsKey(e.getPlayer().getName())){
            e.setCancelled(true);
        }
    }

    @Override
    public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
        if (command.getName().equalsIgnoreCase("pay") && sender instanceof Player) {
            Player player = (Player) sender;

            if (args.length <= 1) {
                player.sendMessage("Usage: /pay <商品名称> <支付方式>");
                return true;
            }

            String text = args[0];
            if (getConfig().getString(text+".name") == null){
                player.sendMessage("商品不存在");
                return true;
            }
            inv.remove(player.getName());
            orders.remove(player.getName());
            items.remove(player.getName());

            new BukkitRunnable() {
                @Override
                public void run() {
                    player.sendMessage(ChatColor.GREEN+"购买商品："+getConfig().getString(text+".name"));
                    player.sendMessage("创建订单中...");
                    String order = getOrderNum();
                    items.put(player.getName(),text);
                    orders.put(player.getName(),order);
                    PaymentRequest paymentRequest = new PaymentRequest(text,args[1],order);
                    inv.put(player.getName(),player.getInventory().getContents());
                    player.getInventory().clear();

                    if (getConfig().getInt("type") == 1){
                        String s = paymentRequest.getResponse().replace("<script>window.location.href='","");
                        s = s.replace("';</script>","");
                        s = getConfig().getString("url") + s;
                        ItemStack mapItem;
                        try {
                            mapItem = QRcode.createQRCodeMap(s,getOrderNum(),"",true);
                        } catch (IOException e) {
                            player.getInventory().setContents(inv.get(player.getName()));
                            inv.remove(player.getName());
                            throw new RuntimeException(e);
                        }
                        player.getInventory().addItem(mapItem);
                        player.sendMessage("请扫码支付!支付后请右键地图");
                    }else{
                        Gson gson = new Gson();
                        HashMap<String,Object> map = gson.fromJson(paymentRequest.getResponse(),HashMap.class);
                        if (Integer.valueOf(map.get("code").toString()) == 1){
                            ItemStack mapItem = null;
                            if (map.containsKey("payurl")){
                                try {
                                    mapItem = QRcode.createQRCodeMap(map.get("payurl").toString(),getOrderNum(),"",true);
                                } catch (IOException e) {
                                    player.getInventory().setContents(inv.get(player.getName()));
                                    inv.remove(player.getName());
                                    throw new RuntimeException(e);
                                }
                            }else if (map.containsKey("qrcode")){
                                try {
                                    mapItem = QRcode.createQRCodeMap(map.get("qrcode").toString(),getOrderNum(),"",true);
                                } catch (IOException e) {
                                    player.getInventory().setContents(inv.get(player.getName()));
                                    inv.remove(player.getName());
                                    throw new RuntimeException(e);
                                }
                            }else if (map.containsKey("img")){
                                try {
                                    mapItem = QRcode.createQRCodeMap("",getOrderNum(),map.get("img").toString(),false);
                                } catch (IOException e){
                                    player.getInventory().setContents(inv.get(player.getName()));
                                    inv.remove(player.getName());
                                    throw new RuntimeException(e);
                                }
                            }
                            player.getInventory().addItem(mapItem);
                            player.sendMessage("请扫码支付!支付后请右键地图");
                        }else{
                            player.sendMessage(ChatColor.RED + "订单创建失败！");
                            player.getInventory().setContents(inv.get(player.getName()));
                            inv.remove(player.getName());

                        }
                    }
                }
            }.runTaskAsynchronously(this);



            return true;
        }
        return false;
    }
    public static String getOrderNum() {
        DateTimeFormatter ofPattern = DateTimeFormatter.ofPattern("yyyyMMddHHmmssSSS");
        String localDate = LocalDateTime.now().format(ofPattern);
        String randomNumeric = RandomStringUtils.randomNumeric(3);
        String orderNum = localDate + randomNumeric;
        return orderNum;
    }

}